package zhongbo.java.air.monitor.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint("/websocket/live")
public class LiveWebsocket {
    private static Set<Session> sessions = new HashSet<>();

    private final Object websocketLock = new Object();

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        log.info("新的WebSocket连接，当前连接数: {}", sessions.size());
        try {
            session.getBasicRemote().sendText("连接成功，等待接收日志...");
        } catch (IOException e) {
            log.error("WebSocket连接建立失败", e);
        }
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        log.info("WebSocket连接关闭，当前连接数: {}", sessions.size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误", error);
        sessions.remove(session);
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到客户端消息: {}", message);
    }
    /**
     * 广播消息
     */
    public void broadcast(String message) {
        synchronized (websocketLock) {
            // 自动清理已关闭的会话
            sessions.removeIf(session -> !session.isOpen());

            for (Session session : sessions) {
                try {
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText(message);
                    }
                } catch (IOException e) {
                    log.error("向会话{}发送消息失败", session.getId(), e);
                    try {
                        session.close();
                    } catch (IOException ex) {
                        log.error("关闭问题会话失败", ex);
                    }
                }
            }
        }
    }
}